
package com.task.base;

import android.app.*;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Formatter;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MemoryActivity extends Activity implements DialogInterface.OnCancelListener {

    TextView tvTotal;

    TextView tvFree;

    TextView tvUsed;

    TextView tvBuffer;

    TextView tvCache;

    Button btClearmemory;

    Dialog mdlgclearing;

    ProgressBar pbClearmemory;

    Button btCancal;

    boolean finished = false;

    private final static int MSG_FAIL = 0;

    private final static int MSG_SUCCESS = 1;

    private final static int RESTART = 2;

    private static final int CLEARING = 3;

    private static final int MSG_MENU_DISMISS = 4;

    Dialog mdlgloading = null;

    private final static int DLG_LOADING = 0;

    private final static int DLG_RESTART = 1;

    private final static int DLG_CLEAR = 2;

    private final static String TAG = "MemoryActivity";

    ActivityManager am;

    ProgressBar mProgress;

    Button cancel;

    TextView text_clear;

    MemoryUseInfo rsInfo = new MemoryUseInfo();

    Float beginFree = 0.0f;

    Float newFree = 0.0f;

    java.text.NumberFormat formater;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memory);
        tvTotal = (TextView) findViewById(R.id.total);
        tvFree = (TextView) findViewById(R.id.free);
        tvUsed = (TextView) findViewById(R.id.used);
        tvBuffer = (TextView) findViewById(R.id.buffer);
        tvCache = (TextView) findViewById(R.id.cache);
        showLoadingMsg();
        am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ((Button) findViewById(R.id.clearmemory)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Util.freeMemory(MemoryActivity.this);
                finished = false;
                showClearProgressDialog();
                getResource();
            }
        });
        formater = java.text.DecimalFormat.getInstance();
        formater.setMaximumFractionDigits(2);
        formater.setMinimumFractionDigits(2);

    }

    private PopupWindow menuPopup;

    private View menuLayout;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("menu");// 必须添加一个，其实用不到

        if (null == menuPopup) {

            menuLayout = getLayoutInflater().inflate(R.layout.options_menu_memory, null);

            menuPopup = new PopupWindow(menuLayout, LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);

            menuPopup.setFocusable(true);// 必须，否则无法点击子view
            menuPopup.setOutsideTouchable(true);// 必须，否则点击其它区域无法关闭
            menuPopup.setBackgroundDrawable(new BitmapDrawable());// 同上
            menuPopup.setAnimationStyle(R.style.MenuAnimation);

            menuPopup.setTouchInterceptor(new OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getY() < 0) {
                        if (menuPopup.isShowing())
                            menuPopup.dismiss();
                    }
                    return false;
                }
            });

            menuLayout.setFocusableInTouchMode(true);// 必须，否则下面的事件不起作用

            menuLayout.setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if ((keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_BACK)
                            && (menuPopup.isShowing())) {
                        menuPopup.dismiss();
                        return true;
                    }
                    return false;
                }
            });

            ((Button) menuLayout.findViewById(R.id.menu_settings))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            mhandler.sendEmptyMessage(MSG_MENU_DISMISS);
                            Intent intent = new Intent(MemoryActivity.this, SettingActivity.class);
                            startActivity(intent);

                        }
                    });

        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menuPopup.isShowing())
            menuPopup.dismiss();
        else
            menuPopup.showAtLocation(findViewById(R.id.LinearLayout1), Gravity.BOTTOM, 0, 0);
        return false;
    }

    protected void onPause() {
        finished = true;
        super.onPause();
    }

    protected void onResume() {
        super.onResume();
        finished = false;
        getResource();

        rsInfo.exeFree(am);
        beginFree = Float.parseFloat(rsInfo.free);
    }

    /**
     * 显示清理内存的进度条对话框
     */
    private void showClearProgressDialog() {
        showDialog(DLG_CLEAR);
        mProgress = (ProgressBar) mdlgclearing.findViewById(R.id.progress_clearmemory);
        mProgress.setProgress(0);
        text_clear = (TextView) mdlgclearing.findViewById(R.id.text_clear);
        text_clear.setText(MemoryActivity.this.getString(R.string.clear_memory_loading));
        cancel = (Button) mdlgclearing.findViewById(R.id.bt_cancal);
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dismissAlertMsg();
                // mhandler.removeMessages(CLEARING);
                // mhandler.removeCallbacks(r);
            }
        });
        // 模拟进度
        mhandler.post(r);
    }

    Runnable r = new Runnable() {
        public void run() {

            int status = 0;
            cancel.setText(getResources().getString(R.string.cancel));
            Message msg = new Message();
            msg.what = CLEARING;
            msg.arg1 = status;
            mhandler.sendMessageDelayed(msg, 100);

        }
    };

    Handler mhandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS:

                    Float total = Float.parseFloat(rsInfo.total);
                    Float free = Float.parseFloat(rsInfo.free);
                    Float buffer = Float.parseFloat(rsInfo.buffer);
                    Float cache = Float.parseFloat(rsInfo.cache);
                    newFree = free;
                    tvTotal.setText(formater.format(new Float(total / 1024)) + " MB");
                    tvFree.setText(formater.format(new Float(free / 1024)) + " MB");
                    tvUsed.setText(formater.format(new Float((total - free) / 1024)) + " MB");
                    tvBuffer.setText(formater.format(new Float(buffer / 1024)) + " MB");
                    tvCache.setText(formater.format(new Float(cache / 1024)) + " MB");
                    dismissLoadingMsg();
                    // dismissAlertMsg();
                    break;
                case MSG_FAIL:
                    dismissLoadingMsg();
                    showRestartMsg();
                    Thread t = new Thread() {
                        public void run() {
                            try {
                                Thread.sleep(3000);
                                mhandler.sendEmptyMessage(RESTART);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    t.start();
                    break;
                case RESTART:
                    Log.e(TAG, "End the Application...");
                    am.restartPackage("com.ztemt.task");
                    // am.forceStopPackage("com.ztemt.task");//强制关闭，用于中兴手机
                    break;

                case CLEARING:

                    int status = msg.arg1;
                    if (status == 100) {
                        cancel.setText(MemoryActivity.this.getString(R.string.finish));
                        Float newValue = new Float(newFree / 1024) - new Float(beginFree / 1024);
                        String releaseValue = formater.format(newValue > 0 ? newValue : 0) + "";
                        text_clear.setText(releaseValue
                                + MemoryActivity.this.getString(R.string.clear_memory_finish));
                    }
                    mProgress.setProgress(status);
                    status += 10;
                    if (status <= 100) {
                        Message m = new Message();
                        m.what = msg.what;
                        m.arg1 = status;
                        mhandler.sendMessageDelayed(m, 500);
                    }
                    break;
                case MSG_MENU_DISMISS:
                    if (menuPopup != null && menuPopup.isShowing()) {
                        menuPopup.dismiss();
                    }
                    break;
            }
        }
    };

    private void getResource() {
        Thread t = new Thread() {
            public void run() {
                while (true) {
                    if (finished) {
                        break;
                    }
                    if ((!rsInfo.exeFree(am)) || (!rsInfo.exeTop())) {
                        mhandler.sendEmptyMessage(MSG_FAIL);
                    } else {
                        mhandler.sendEmptyMessage(MSG_SUCCESS);
                    }
                }
            }
        };
        t.start();
    }

    private void showLoadingMsg() {
        showDialog(DLG_LOADING);
    }

    private void showRestartMsg() {
        showDialog(DLG_RESTART);
    }

    private void dismissLoadingMsg() {
        if ((mdlgloading != null) && (mdlgloading.isShowing())) {
            dismissDialog(DLG_LOADING);
        }
    }

    private void dismissAlertMsg() {
        if ((mdlgclearing != null) && (mdlgclearing.isShowing())) {
            dismissDialog(DLG_CLEAR);
        }
    }

    @Override
    public Dialog onCreateDialog(int id) {
        switch (id) {
            case DLG_LOADING:
                ProgressDialog pdlg = new ProgressDialog(this);
                pdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                pdlg.setMessage(getText(R.string.loading));
                pdlg.setIndeterminate(true);
                pdlg.setCanceledOnTouchOutside(false);
                // pdlg.setOnCancelListener(this);
                mdlgloading = pdlg;
                return pdlg;
            case DLG_RESTART:
                Dialog dlg = new Dialog(this);
                dlg.setTitle(getText(R.string.restart));
                dlg.setOnCancelListener(this);
                return dlg;
            case DLG_CLEAR:// 释放内存
                LayoutInflater inflater = getLayoutInflater();
                View linearlayout = inflater.inflate(R.layout.clear_memory_view, null);
                pbClearmemory = (ProgressBar) this.findViewById(R.id.progress_clearmemory);
                btCancal = (Button) this.findViewById(R.id.bt_cancal);
                mdlgclearing = new AlertDialog.Builder(this).setInverseBackgroundForced(true)
                        .setIcon(R.drawable.recycle).setTitle(R.string.clear_memory)
                        .setView(linearlayout).create();
                mdlgclearing.setOnDismissListener(new OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        mhandler.removeCallbacks(r);
                        mhandler.removeMessages(CLEARING);
                    }
                });
                return mdlgclearing;
            default:
                return null;
        }
    }

    private String getAvailMemory() {// 获取android当前可用内存大小

        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(getBaseContext(), mi.availMem);// 将获取的内存大小规格化
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        mdlgloading = null;
        finish();
    }

}
